# -*- coding: utf-8 -*-
import sys
import yaml
import datetime
import ConnMySql
import SqlCollect
from JKlog import *

reload(sys)
sys.setdefaultencoding('utf-8')


class addMoney:
    def __init__(self, strConfig, UID, MONEY):
        self.UID = UID
        self.MONEY = MONEY
        self.fr = open('Config.yml', 'r')
        self.fconfig = yaml.load(self.fr)
        self.realConfig = self.fconfig[strConfig]

    def addmoney(self):
        flag = False  # acc 库初始化
        account = self.realConfig["account"]
        host = account["host"]
        user = account["user"]
        pwd = account["password"]
        name = account["name"]
        port = account["port"]
        charset = account["charset"]
        accDb = ConnMySql.ConnMySql(host, port, name, user, pwd, charset)
        # 全局变量
        ACCOUNT_ID = False
        # 日志

        logger = JKLogger('Add_Money' + "_" + self.UID)


        try:
            # 获取 ACCOUNT_ID
            # 以 uid 删除  获取变量值 , 获取 account_id
            sql = 'SELECT ID FROM' + SqlCollect.SqlCollect.sqlacc01 + "'" + self.UID + "'"
            result = accDb.fetch_all(sql)
            if result and len(result) == 1:
                ACCOUNT_ID = result[0]['ID']
                logger.log(u'获得的ACCOUNT_ID参数值为: %s ' % ACCOUNT_ID)
            else:
                logger.log(u'获得的ACCOUNT_ID参数值为：空 ')
            # 往 tbl_pre_deposit_change 表插入数据
            CODE = "Test" + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            TYPE = "patient"
            BUSINESS_TYPE = "recharge"
            SERVER_TYPE = "alipay"
            AMOUNT = str(self.MONEY)
            AVALIABLE_AMOUNT = str(self.MONEY)
            FROZEN_AMOUNT = "0"
            FROZEN_ALL_FLAG = "10"
            VALID_FLAG = "true"
            REMARK = "测试接口添加"
            CREATE_TIME = datetime.datetime.now()
            UPDATE_TIME = datetime.datetime.now()
            # 拼接 SQL

            InsertSQL = 'INSERT INTO tbl_pre_deposit_change(CODE,ACCOUNT_ID,TYPE,BUSINESS_TYPE,SERVER_TYPE,AMOUNT,AVALIABLE_AMOUNT,FROZEN_AMOUNT,FROZEN_ALL_FLAG,VALID_FLAG,REMARK,CREATE_TIME,UPDATE_TIME) VALUES '\
                '("{0}",{1},"{2}","{3}","{4}",{5},{6},{7},"{8}","{9}","{10}","{11}","{12}")'.format(CODE,ACCOUNT_ID,TYPE,BUSINESS_TYPE,SERVER_TYPE,AMOUNT,AVALIABLE_AMOUNT,FROZEN_AMOUNT,FROZEN_ALL_FLAG,VALID_FLAG,REMARK,CREATE_TIME,UPDATE_TIME)
            # 执行插入数据库
            res = accDb.insert(InsertSQL)
            if res:
                accDb.commit()
                logger.log(u'用户' + str(self.UID) + u'充值成功，充值金额： "%s" ' % AMOUNT)
            else:
                logger.log(u'用户' + str(self.UID) + u'充值失败！')
            # 关闭连接
            accDb.close()
            flag = True
        except Exception as data:
            logger.log(data.message)
            flag = False
        logger.delLogger()
        return flag
